import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Input, AutoComplete, Button, Tooltip } from 'antd';
import { SearchOutlined, ClearOutlined, HistoryOutlined } from '@ant-design/icons';
import { searchService } from '../../../services/search';
import { SearchHistory } from '../../../services/search/types';

interface SearchInputProps {
  value: string;
  onChange: (value: string) => void;
  onSearch: (query: string) => void;
  placeholder?: string;
  showSuggestions?: boolean;
  loading?: boolean;
  className?: string;
}

export const SearchInput: React.FC<SearchInputProps> = ({
  value,
  onChange,
  onSearch,
  placeholder = '搜索文档内容...',
  showSuggestions = true,
  loading = false,
  className
}) => {
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [searchHistory, setSearchHistory] = useState<SearchHistory[]>([]);
  const [showHistory, setShowHistory] = useState(false);
  const debounceRef = useRef<NodeJS.Timeout>();

  // 加载搜索历史
  useEffect(() => {
    loadSearchHistory();
  }, []);

  const loadSearchHistory = async () => {
    try {
      const history = await searchService.getSearchHistory();
      setSearchHistory(history.slice(0, 10)); // 只显示前10条
    } catch (error) {
      console.error('[SearchInput] 加载搜索历史失败:', error);
    }
  };

  // 防抖获取搜索建议
  const getSuggestions = useCallback(async (query: string) => {
    if (!query.trim() || query.length < 2 || !showSuggestions) {
      setSuggestions([]);
      return;
    }

    try {
      const results = await searchService.getSuggestions(query);
      setSuggestions(results);
    } catch (error) {
      console.error('[SearchInput] 获取搜索建议失败:', error);
      setSuggestions([]);
    }
  }, [showSuggestions]);

  // 处理输入变化
  const handleInputChange = (newValue: string) => {
    onChange(newValue);
    
    // 清除之前的防抖
    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }

    // 设置新的防抖
    debounceRef.current = setTimeout(() => {
      getSuggestions(newValue);
    }, 300);
  };

  // 处理搜索执行
  const handleSearch = (searchValue?: string) => {
    const query = searchValue || value;
    if (query.trim()) {
      onSearch(query.trim());
      setShowHistory(false);
    }
  };

  // 处理清除按钮
  const handleClear = () => {
    onChange('');
    setSuggestions([]);
    setShowHistory(false);
  };

  // 处理焦点事件
  const handleFocus = () => {
    if (!value.trim() && searchHistory.length > 0) {
      setShowHistory(true);
    }
  };

  // 处理失焦事件
  const handleBlur = () => {
    // 延迟隐藏历史，以便点击历史项
    setTimeout(() => {
      setShowHistory(false);
    }, 200);
  };

  // 准备自动完成选项
  const getAutoCompleteOptions = () => {
    const options: { value: string; label: React.ReactNode }[] = [];

    // 显示搜索历史
    if (showHistory && !value.trim()) {
      searchHistory.forEach(history => {
        options.push({
          value: history.query,
          label: (
            <div className="search-history-item">
              <HistoryOutlined style={{ marginRight: 8, color: '#999' }} />
              <span>{history.query}</span>
              <span style={{ marginLeft: 'auto', color: '#999', fontSize: '12px' }}>
                {history.resultCount} 结果
              </span>
            </div>
          )
        });
      });
    }

    // 显示搜索建议
    if (!showHistory && suggestions.length > 0) {
      suggestions.forEach(suggestion => {
        options.push({
          value: suggestion,
          label: (
            <div className="search-suggestion-item">
              <SearchOutlined style={{ marginRight: 8, color: '#1890ff' }} />
              <span>{suggestion}</span>
            </div>
          )
        });
      });
    }

    return options;
  };

  // 键盘事件处理
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSearch();
    } else if (e.key === 'Escape') {
      handleClear();
    }
  };

  return (
    <div className={`search-input-container ${className || ''}`}>
      <AutoComplete
        value={value}
        options={getAutoCompleteOptions()}
        onSelect={handleSearch}
        onSearch={handleInputChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        style={{ width: '100%' }}
        popupClassName="search-dropdown"
      >
        <Input
          placeholder={placeholder}
          onKeyDown={handleKeyDown}
          suffix={
            <div className="search-input-suffix">
              {value && (
                <Tooltip title="清除">
                  <Button
                    type="text"
                    size="small"
                    icon={<ClearOutlined />}
                    onClick={handleClear}
                    className="clear-button"
                  />
                </Tooltip>
              )}
              <Tooltip title="搜索">
                <Button
                  type="primary"
                  size="small"
                  icon={<SearchOutlined />}
                  onClick={() => handleSearch()}
                  loading={loading}
                  className="search-button"
                />
              </Tooltip>
            </div>
          }
          className="search-input"
        />
      </AutoComplete>

      <style jsx>{`
        .search-input-container {
          width: 100%;
        }

        .search-input-container :global(.search-input) {
          border-radius: 6px;
        }

        .search-input-container :global(.search-input-suffix) {
          display: flex;
          align-items: center;
          gap: 4px;
        }

        .search-input-container :global(.clear-button) {
          color: #999;
          opacity: 0.7;
          transition: opacity 0.2s;
        }

        .search-input-container :global(.clear-button:hover) {
          opacity: 1;
          color: #ff4d4f;
        }

        .search-input-container :global(.search-button) {
          min-width: 32px;
        }

        .search-input-container :global(.search-dropdown) {
          max-height: 300px;
          overflow-y: auto;
        }

        .search-input-container :global(.search-history-item),
        .search-input-container :global(.search-suggestion-item) {
          display: flex;
          align-items: center;
          padding: 4px 0;
          width: 100%;
        }

        .search-input-container :global(.search-history-item:hover),
        .search-input-container :global(.search-suggestion-item:hover) {
          background-color: #f5f5f5;
        }
      `}</style>
    </div>
  );
};

export default SearchInput;